<template>
  <div style="padding: 0 17px">
    <Breadcrumb/>
    <div>
      <el-button type="primary" style="margin-top: 20px;color: #fff;font-size: 12px;background-color: #1890ff;" @click="addItem">添加角色</el-button>
    </div>
    <div>
      <el-table :data="tableData" :row-style="{ height: '77px' }" border style="width: calc(100vw - 240px);margin-top: 20px;height: 70vh;color: #909399;font-size: 15px;">
        <el-table-column prop="id" label="ID" width="100"/>
        <el-table-column prop="rolename" label="名称" width="150"/>
        <el-table-column prop="description" label="描述" width="auto"/>
        <el-table-column align="center" label="操作" fixed="right" width="170">
          <template v-slot="scope">
            <el-button type="primary" size="small" icon="Edit" @click="editItem(scope.row)">编辑</el-button>
            <el-button v-if="this.userInformation.role === 1" type="danger" size="small" icon="Delete" @click="deleteItem(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :background="true"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog :close-on-click-modal="false" v-model="operationItemDialog" @open="handleDialogOpened" title="角色操作" width="700">
      <el-form :model="form" :rules="rules" ref="form" label-position="right" class="demo-roleForm">
        <el-form-item label="角色名称" prop="rolename">
          <el-input v-model="form.rolename" class="input-size" placeholder="角色名称"></el-input>
        </el-form-item>
        <el-form-item label="菜单" prop="description">
          <div class="tree-container">
            <div v-for="(node,index) in rootNodes" :key="node.id" class="tree-wrapper">
              <el-tree
                  :ref="`treeRef${index}`"
                  :data="[node]"
                  show-checkbox
                  check-strictly
                  node-key="id"
                  highlight-current
                  :props="defaultProps"
                  @check="handleNodeChecked"
              />
            </div>
          </div>
        </el-form-item>
        <el-form-item label="功能菜单描述">
          <el-input type="textarea" v-model="form.description" class="input-size" placeholder="自动填充"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button style="font-size: 12px" type="primary" @click="submitForm('form')">提交</el-button>
          <el-button style="font-size: 12px;color: #606266" @click="reset('form')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request.js";
import Breadcrumb from "@/components/Breadcrumb.vue";

export default {
  name: "Role",
  components: {Breadcrumb},
  data() {
    return{
      operationItemDialog: false,
      userInformation:JSON.parse(localStorage.getItem("user")),
      tableData:[],
      rules: {
        rolename: [
          {required: true, message: '请输入名称', trigger: 'blur'},
        ],
        description: [
          {required: true, message: '请选择功能菜单', trigger: 'blur'},
        ],
      },
      form:{},
      defaultProps:{
        children: 'menuDtos',
        label: 'menuName',
        value: 'id'
      },
      menuOperations:[],
      currentPage: 1,
      pageSize: 10,
      total: 10,
      defaultCheckedKeys: [] // 要在初始化时选中的节点ID
    }
  },
  computed: {
    rootNodes() {
      return this.menuOperations;
    }
  },
  created() {
    this.load()
  },
  methods: {
    // 添加
    addItem(){
      this.getMenuOperations()
      this.operationItemDialog = true;
      this.setCheckedNodes()
    },
    // 编辑
    async editItem(scope) {
      // 获取所有菜单
      await this.getMenuOperations()
      // 获取已有菜单
      this.getRoleMenu(scope.id)
      Object.assign(this.form, scope)
      this.operationItemDialog = true
      this.setCheckedNodes()
    },
    // 获取角色菜单
    getRoleMenu(roleId){
      request.get(`/role-menu/findAllMenu/${roleId}`).then(res=>{
        this.defaultCheckedKeys = res.data
      })
    },
    // 提交
    submitForm(val){
      this.handleDialogClosed()
      this.$refs[val].validate((valid) => {
        if (valid) {
          request.post("/role/edit",this.form).then(res=>{
            if (res.code==='200'){
              this.operationItemDialog=false
              this.$message({
                message:"成功",
                type:"success"
              })
              this.load()
            }else {
              this.$message.error("操作失败"+res.msg)
            }
          })
        }
      })
    },
    // 取消
    reset(val){
      this.operationItemDialog = false;
      this.defaultCheckedKeys=[]
      this.form={};
      this.$refs[val].resetFields();
    },
    handleSizeChange(pageSize) {   // 改变当前每页的个数触发
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {  // 改变当前页码触发
      this.currentPage = pageNum
      this.load()
    },
    // 删除
    deleteItem(scope){
      this.$confirm('是否确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request.get("/role/delete/"+scope).then(res=>{
          if (res.code==='200'){
            this.$message.success("成功")
            this.load()
          }else {
            this.$message.error("删除失败，"+res.msg)
          }
        })
      });
    },
    // 搜索及初始化
    load(){
      this.form = {}
      this.defaultCheckedKeys=[]
      request.get("/role/page?pageNum=" + this.currentPage + "&pageSize=" + this.pageSize).then(res => {
        if (res.code === '200') {
          for (let key in res.data) {
            if (key === "records") {
              this.tableData = res.data[key];
            } else if (key === "total") {
              this.total = res.data[key];
            }
          }
        } else {
          this.$message.error("错误"+res.msg)
        }
      })
    },
    // 获取菜单
    async getMenuOperations(){
      if (this.menuOperations.length===0){
        await request.get("/menu/all").then(res=>{
          this.menuOperations.push(...res.data)
        })
      }
    },
    handleDialogOpened() {
      setTimeout(()=>this.setCheckedNodes(),100)
    },
    handleNodeChecked(checkedKeys, halfCheckedKeys) {
      if (!Array.isArray(checkedKeys)) {
        checkedKeys = [];
      }
      this.updateCheckedKeys(checkedKeys);
      this.defaultCheckedKeys = checkedKeys;
    },
    updateCheckedKeys(checkedKeys) {
      const allCheckedKeys = new Set(checkedKeys);
      const checkParentNodes = (node) => {
        if (node.children && node.children.length > 0) {
          const allChildrenChecked = node.children.every(child => allCheckedKeys.has(child.id));
          if (allChildrenChecked) {
            allCheckedKeys.add(node.id);
          }
          node.children.forEach(child => checkParentNodes(child));
        }
      };

      this.menuOperations.forEach(rootNode => checkParentNodes(rootNode));

      const updateParents = (node) => {
        if (node.children && node.children.length > 0) {
          node.children.forEach(child => updateParents(child));
          if (node.children.some(child => allCheckedKeys.has(child.id))) {
            allCheckedKeys.add(node.id);
          }
        }
      };
      this.menuOperations.forEach(rootNode => updateParents(rootNode));

      this.defaultCheckedKeys = Array.from(allCheckedKeys);
      this.handleDialogClosed()
    },
    setCheckedNodes() {
      this.rootNodes.forEach((node, index) => {
        const treeRef = this.$refs[`treeRef${index}`][0];
        if (treeRef) {
          treeRef.setCheckedKeys(this.defaultCheckedKeys, true);
        }
      });
    },
    handleDialogClosed() {
      this.form.menuIds = [];
      let checkedName = ""
      this.rootNodes.forEach((node, index) => {
        const treeRef = this.$refs[`treeRef${index}`][0];
        if (treeRef) {
          const checkedKeys = treeRef.getCheckedKeys();
          const checkedNodes = treeRef.getCheckedNodes();
          if (checkedNodes.length > 0){
            checkedNodes.forEach(node => {
              checkedName=checkedName+node.menuName+","
            })
          }
          this.form.menuIds.push(...checkedKeys);
        }
      });
      this.form.description=checkedName
    }
  }
}
</script>

<style scoped>
:deep(.el-table th .cell)  {
  font-weight: 700
}
:deep(.el-form-item__label) {
  font-size: 14px;
  font-weight: 700
}
.input-size {
  font-size: 13px;
}
.tree-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px; /* 控制每个树之间的间距 */
}

.tree-wrapper {
  min-width: 150px; /* 控制每个树的最小宽度 */
  flex-grow: 1; /* 让每个树根据需要扩展 */
}
</style>
